package com.dnw.shyfunny;

import android.Manifest;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.dnw.adapter.ProgramImagesAdapter;
import com.dnw.base.BaseActivity;
import com.dnw.listener.PermissionListener;
import com.dnw.modle.Program;
import com.dnw.modle.Result;
import com.dnw.presenter.ProgramDownloadPresenter;
import com.dnw.util.ConstanceValue;
import com.dnw.util.DownloadProgressReceiver;
import com.dnw.util.GlideUtils;
import com.dnw.util.RecommendProgramUtil;
import com.dnw.util.UIUtils;
import com.dnw.view.IProgramDownLoadView;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.notification.BaseNotificationItem;
import com.liulishuo.filedownloader.notification.FileDownloadNotificationHelper;
import com.liulishuo.filedownloader.notification.FileDownloadNotificationListener;
import com.liulishuo.filedownloader.util.FileDownloadHelper;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import flyn.Eyes;

/**
 * Created by yangyu on 2017/11/16.
 * 羞羞的应用
 */

public class ProgramDetailActivity extends BaseActivity<ProgramDownloadPresenter> implements IProgramDownLoadView, DownloadProgressReceiver.Message {
    @Bind(R.id.tv_author)
    TextView  tvAuthor;
    @Bind(R.id.bt_download)
    Button    btDownload;
    @Bind(R.id.iv_icon)
    ImageView ivIcon;
    @Bind(R.id.tv_developer)
    TextView  tvDeveloper;
    @Bind(R.id.tv_name)
    TextView  tvName;
    @Bind(R.id.tv_category)
    TextView  tvCategory;
    @Bind(R.id.tv_supportedPltf)
    TextView  tvSupportedPltf;
    @Bind(R.id.rb_score)
    RatingBar rbScore;
    @Bind(R.id.tv_scoreTimes)
    TextView  tvScoreTimes;
    @Bind(R.id.gv_images)
    GridView  gvImages;
    @Bind(R.id.tv_descpt)
    TextView  tvDescpt;

    Program              mProgram;
    ProgramImagesAdapter mProgramImagesAdapter;
    private int downloadId = 0;
    String                   appFile;
    DownloadProgressReceiver mDownloadProgressReceiver;
    boolean isDownload = false;

    @Override
    public void initView() {
        Eyes.setStatusBarColor(this, UIUtils.getColor(R.color.a));
    }

    @Override
    public void initData() {
        mProgram = (Program) getIntent().getSerializableExtra("program");
        isDownload = getIntent().getBooleanExtra("download", false);
        tvAuthor.setText(mProgram.name);
        GlideUtils.load(this, mProgram.iconDownloadUrl, ivIcon, R.color.divider);//设置缩略图
        tvDeveloper.setText(mProgram.developer);
        tvCategory.setText(mProgram.category);
        tvName.setText(mProgram.name);
        tvDescpt.setText(mProgram.descpt);
        tvSupportedPltf.setText(mProgram.supportedPltf);
        tvScoreTimes.setText("(" + mProgram.scoreTimes + "次评分)");
        rbScore.setRating(mProgram.score);
        mProgramImagesAdapter = new ProgramImagesAdapter(this, mProgram.images.split(";"));
        gvImages.setAdapter(mProgramImagesAdapter);
        appFile = Environment.getExternalStorageDirectory().getPath() + File.separator + "xiudou_app" + File.separator + mProgram.name + ".apk";
        mDownloadProgressReceiver = new DownloadProgressReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstanceValue.RECOMMEND_APP_DOWNLOAD_PROGRESS);
        registerReceiver(mDownloadProgressReceiver, intentFilter);
        mDownloadProgressReceiver.setMessage(this);
        if (isDownload && (RecommendProgramUtil.checkProgramStatus(this, mProgram.name) == RecommendProgramUtil.UNDOWNLOAD)) {
            mPresenter.getProgramDownloadResult(mProgram.id);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        switch (RecommendProgramUtil.checkProgramStatus(this, mProgram.name)) {
            case RecommendProgramUtil.UNDOWNLOAD:
                btDownload.setText("立即下载");
                btDownload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPresenter.getProgramDownloadResult(mProgram.id);
                    }
                });
                break;
            case RecommendProgramUtil.DOWNLOAD:
                btDownload.setText("立即安装");
                btDownload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(appFile)), "application/vnd.android.package-archive");
                        startActivity(intent);
                    }
                });

                break;
            case RecommendProgramUtil.INSTALLED:
                btDownload.setText("立即打开");
                btDownload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        RecommendProgramUtil.startApplicationWithName(ProgramDetailActivity.this, mProgram.name);
                    }
                });
                break;
        }
    }

    @Override
    protected ProgramDownloadPresenter createPresenter() {
        return new ProgramDownloadPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_program_detail;
    }

    @OnClick({R.id.tv_back, R.id.bt_download})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.bt_download:
                mPresenter.getProgramDownloadResult(mProgram.id);
                break;
        }
    }

    @Override
    public void onGetProgramDownLoadSuccess(Result result) {
        if (result.code == 0) {
            requestRuntimePermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onGranted() {
                    if (downloadId == 0) {
                        downloadId = FileDownloader.getImpl().create(mProgram.downloadUrl)
                                .setPath(appFile)
                                .setListener(new NotificationListener(new FileDownloadNotificationHelper<NotificationItem>()))
                                .start();
                        btDownload.setEnabled(false);
                    }
                }

                @Override
                public void onDenied(List<String> deniedPermissions) {
                    UIUtils.showToast(getString(R.string.write_storage_permission_deny));
                }
            });

        } else {
            UIUtils.showToast(result.msg);
        }
    }

    @Override
    public void onError() {

    }

    @Override
    public void update(String name, int progress) {
        if (mProgram.name.equals(name)) {
            btDownload.setText("正在下载(" + progress + "%)");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mDownloadProgressReceiver);     //注销广播接收器
    }

    public class NotificationListener extends FileDownloadNotificationListener {

        private static final String TAG = "NotificationListener";

        public NotificationListener(FileDownloadNotificationHelper helper) {
            super(helper);
        }

        @Override
        protected BaseNotificationItem create(BaseDownloadTask task) {
            return new ProgramDetailActivity.NotificationItem(task.getId(),
                    mProgram.name, mProgram.slogan);
        }

        @Override
        public void destroyNotification(BaseDownloadTask task) {
            super.destroyNotification(task);
            downloadId = 0;
            if (task.getStatus() == FileDownloadStatus.completed) {
                File file= new File(appFile);
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri =
                        FileProvider.getUriForFile(ProgramDetailActivity.this, "com.dnw.shyfunny.fileprovider", file);

                Intent intent = new Intent(Intent.ACTION_VIEW);
                // 由于没有在Activity环境下启动Activity,设置下面的标签
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                startActivity(intent);
            }
            btDownload.setText("立即安装");
            btDownload.setEnabled(true);
        }

    }

    public class NotificationItem extends BaseNotificationItem {

        PendingIntent              pendingIntent;
        NotificationCompat.Builder builder;

        private NotificationItem(int id, String title, String desc) {
            super(id, title, desc);
            builder = new NotificationCompat.
                    Builder(FileDownloadHelper.getAppContext());

            builder.setDefaults(Notification.DEFAULT_LIGHTS)
                    .setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_MIN)
                    .setContentTitle(getTitle())
                    .setContentText(desc)
                    .setSmallIcon(R.mipmap.ic_launcher);
        }

        @Override
        public void show(boolean statusChanged, int status, boolean isShowProgress) {
            long total = 100;
            int progress = 0;
            if (getTotal() != 0) {
                progress = (int) ((float) getSofar() / (float) getTotal() * 100);
            }
            builder.setContentTitle(getTitle() + "(" + progress + "%)")
                    .setContentText(getDesc());
            if (statusChanged) {
                builder.setTicker(getDesc());
            }
            builder.setProgress(getTotal(), getSofar(), !isShowProgress);
            getManager().notify(getId(), builder.build());
            Intent intent = new Intent();
            intent.setAction(ConstanceValue.RECOMMEND_APP_DOWNLOAD_PROGRESS);
            intent.putExtra("name", getTitle());
            intent.putExtra("progress", progress);
            FileDownloadHelper.getAppContext().sendBroadcast(intent);
        }

    }
}
